package com.ldl.distributelock.zk;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.CountDownLatch;

@Component
public class ZkClient {
    ZooKeeper zooKeeper = null;

    // 在构造对象之后初始化连接
    @PostConstruct
    public void init() {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            zooKeeper = new ZooKeeper("127.0.0.1:2181", 30000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                Event.KeeperState state = watchedEvent.getState();
                if (Event.KeeperState.SyncConnected.equals(state) && Event.EventType.None.equals(watchedEvent.getType())) {
                    System.out.println("获取连接了吗" + watchedEvent);
                    countDownLatch.countDown();
                } else if (Event.KeeperState.Closed.equals(state)) {
                    System.out.println("关闭连接");
                }
            }});
            countDownLatch.await();
            System.out.println("一顿操作");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ZkDistributedLock getLock(String lockName) {
        return new ZkDistributedLock(lockName, zooKeeper);
    }

    //在销毁对象之前断开连接
    @PreDestroy
    public void destroy() throws InterruptedException {
        if (zooKeeper != null) {
            zooKeeper.close();
        }
    }
}
